package by.parfen.messages.webapp.receive;

import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.time.Duration;

import by.parfen.messages.services.ver2.Server;
import by.parfen.messages.webapp.BaseLayout;
import by.parfen.messages.webapp.app.BasicAuthenticationSession;

public class ReceiveMessagePage extends BaseLayout {

	private boolean refreshStopped = true;

	@Override
	protected void onInitialize() {
		super.onInitialize();

		final Form<Void> sendForm = new Form<Void>("sendForm");
		add(sendForm);

		sendForm.add(new SubmitLink("sumbitLink") {

			@Override
			public void onSubmit() {
				super.onSubmit();

				BasicAuthenticationSession.get().setServer(new Server());
				BasicAuthenticationSession.get().getServer().setLastTextMessage(null);

			}
		});

		Model<String> infoModel = new Model<String>() {
			private String res = "";

			public String getObject() {
				Server server = BasicAuthenticationSession.get().getServer();
				if (server != null) {
					res = server.getLastTextMessage();
					if (res != null && res.length() > 0) {
						refreshStopped = true;
					}
				}
				return res;
			}
		};
		final Label info = new Label("info", infoModel);
		info.setOutputMarkupId(true);
		sendForm.add(info);

		add(new AbstractAjaxTimerBehavior(Duration.milliseconds(5000)) {

			@Override
			protected void onTimer(AjaxRequestTarget target) {
				if (!refreshStopped) {
					target.add(info);
				}
			}
		});

	}

}
